<?php

class m_usergroups extends CI_Model{
	
	function _list($data){
		extract($data);
		$sql = "SELECT 
					group_name,
					group_desc,
					group_id,
					menus
				FROM s_usergroups LEFT JOIN
				(SELECT s_usergroups_id, GROUP_CONCAT(s_menus_id) as menus FROM s_role GROUP BY s_usergroups_id) v_rolegroup
				ON s_usergroups_id = group_id
				WHERE 
					usergroups_sys_active = '1'
		";
		
		if (@$group_name != "") $sql .= " AND group_name like '%".@$group_name."%'";
		if (@$group_desc != "") $sql .= " AND group_desc like '%".@$group_desc."%'";
		
		$query = $this->db->query($sql);
		$records = $query->num_rows();
		
		$sql = "SELECT * FROM (".$sql.") k LIMIT ".(($page - 1) * $rows).",".$rows;
		$query = $this->db->query($sql);
		$result = $query->result();
		
		return '{ 
		  "total": "'.ceil($records / $rows).'", 
		  "page": "'.$page.'", 
		  "records": "'.$records .'",
		  "rows" : '.json_encode($result).'
		}';
	}
	
	function _insert($data,$menus){
		$this->db->insert('s_usergroups',$data);
		$id = $this->db->insert_id();
		
		$this->db->where('s_usergroups_id',$id);
		$this->db->delete('s_role');
		foreach($menus as $menu){
			$datamenus["s_menus_id" ] = $menu;
			$datamenus["s_usergroups_id" ] = $id;
			$this->db->insert('s_role',$datamenus);
		}
		return 1;
	}
	
	function _update($data,$id,$menus){
		$this->db->where('group_id',$id);
		$this->db->update('s_usergroups',$data);
		
		$this->db->where('s_usergroups_id',$id);
		$this->db->delete('s_role');
		foreach($menus as $menu){
			$datamenus["s_menus_id" ] = $menu;
			$datamenus["s_usergroups_id" ] = $id;
			$this->db->insert('s_role',$datamenus);
		}
		return 1;
	}
	
	function _delete($data,$id){
		$this->db->where('group_id',$id);
		$this->db->update('s_usergroups',$data);
		return 1;
	}
	
	function s_menus(){
		$sql = "SELECT menus_id , menus_label FROM s_menus WHERE menus_sys_active = 1 AND menus_parent <> -1";
		$query = $this->db->query($sql);
		return $query->result();
	}
}